const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const MassageChairProtocol = require('./src/protocols/MassageChairProtocol');

class MainProcess {
  constructor() {
    this.mainWindow = null;
    this.protocol = new MassageChairProtocol();
    this.initializeApp();
  }

  initializeApp() {
    app.whenReady().then(() => {
      this.createWindow();
      this.setupIpcHandlers();
      
      app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
          this.createWindow();
        }
      });
    });

    app.on('window-all-closed', () => {
      if (process.platform !== 'darwin') {
        app.quit();
      }
    });
  }

  createWindow() {
    this.mainWindow = new BrowserWindow({
      width: 1200,
      height: 800,
      webPreferences: {
        nodeIntegration: false,
        contextIsolation: true,
        preload: path.join(__dirname, 'src/preload/preload.js'),
        webSecurity: false // 需要禁用以支持Web Bluetooth API
      },
      icon: path.join(__dirname, 'assets/icon.png'),
      title: '按摩椅蓝牙控制器'
    });

    this.mainWindow.loadFile('src/renderer/index.html');

    // 开发模式下打开开发者工具
    if (process.argv.includes('--dev')) {
      this.mainWindow.webContents.openDevTools();
    }
  }

  setupIpcHandlers() {
    // 创建按摩椅指令
    ipcMain.handle('protocol:createCommand', async (event, commandType, value) => {
      try {
        const command = this.protocol.createCommand(commandType, value);
        return { success: true, command: Array.from(command) }; // 转换为数组传输
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // 创建心率指令
    ipcMain.handle('protocol:createHeartRateCommand', async (event, action) => {
      try {
        const command = this.protocol.createHeartRateCommand(action);
        return { success: true, command: Array.from(command) };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // 解析接收到的数据
    ipcMain.handle('protocol:parseData', async (event, dataArray) => {
      try {
        const buffer = Buffer.from(dataArray);
        const parsedData = this.protocol.parseReceivedData(buffer);
        return { success: true, data: parsedData };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });

    // 解析状态数据
    ipcMain.handle('protocol:parseStatus', async (event, dataArray) => {
      try {
        const buffer = Buffer.from(dataArray);
        const status = this.protocol.parseStatus(buffer);
        return { success: true, status };
      } catch (error) {
        return { success: false, error: error.message };
      }
    });
  }
}

// 启动应用
new MainProcess();